package com.ssyc.student.activity;

import android.animation.ObjectAnimator;
import android.content.Intent;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ssyc.common.base.BaseActivity;
import com.ssyc.common.base.BaseApplication;
import com.ssyc.common.base.SpKeys;
import com.ssyc.common.glide.ImageUtil;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.SPUtil;
import com.ssyc.common.utils.ScreenUtils;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.ZzHorizontalProgressBar;
import com.ssyc.student.R;
import com.ssyc.student.bean.HomeInfo;
import com.ssyc.student.bean.ResultInfo;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;

/**
 * 学生端拜访好友的界面
 */
public class StudentVisitFriendActivity extends BaseActivity implements View.OnClickListener {

    //加载框布局
    private RelativeLayout rlLoading;

    //背景
    private ImageView lvBg;

    //等级
    private TextView tvLever;

    //展示精力的进度条
    private ZzHorizontalProgressBar pbVigor;

    //展示精力值的文字
    private TextView tvEnergy;

    //头像
    private CircleImageView lvHead;
    //金币数
    private TextView tvGold;
    //星星数
    private TextView tvStar;
    //喂食
    private ImageView lvFeed;
    //PK
    private ImageView lvPk;
    //回家
    private ImageView lvHome;
    //好友
    private ImageView lvFriends;
    //消息
    private ImageView lvMessage;

    //屏幕中间包含所有宠物动画的相对布局
    private RelativeLayout rlAllPet;
    //宠物的底图和套装
    private ImageView ivClothing;
    //帽子
    private ImageView ivHat;
    //眼镜
    private ImageView ivGrass;
    //项链
    private ImageView ivJingshi;


    //控制左右移动的标识
    private boolean isleft = true;

    //控制循环的变量
    private boolean isWhile = true;

    //用于是否发送移动消息的标致
    private boolean isSend = true;

    //是否是第一次进入
    private boolean isFirst = true;

    //动画对象
    private ObjectAnimator animator;

    //拜访对象账号
    private String userid;

    //拜访对象姓名
    private String toname;

    //拜访宠物姓名
    private String topetname;

    //拜访对象JSON数据
    private String json;

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    protected int getContentLayout() {
        return R.layout.student_activity_visit_friend;
    }

    @Override
    protected void init() {
        showContent();

        //初始化视图
        initView();

        //接受数据
        initIntent();

        //请求服务器获取首页数据
        http();
    }

    /**
     * 接收数据
     */
    private void initIntent() {

        userid = getIntent().getStringExtra("userid");
        toname = getIntent().getStringExtra("toname");
    }


    /**
     * 初始化视图的方法
     */
    private void initView() {
        lvBg = findViewById(R.id.lv_bg);
        tvLever = findViewById(R.id.tv_lever);
        //精力值
        tvEnergy = findViewById(R.id.tv_energy);
        //动态适配图片的大小
        int screenWidth = ScreenUtils.getScreenWidth(this);
        //屏幕宽度的五分之一减去左右边距
        int lvBottomItemWidth = (screenWidth - 16) / 5 - 24;
        RelativeLayout.LayoutParams lpBottom = new RelativeLayout.LayoutParams(lvBottomItemWidth, lvBottomItemWidth);
        lpBottom.addRule(RelativeLayout.CENTER_IN_PARENT);
        //设置底部的菜单图片的大小

        //展示精力的进度条
        pbVigor = findViewById(R.id.pb_vigor);
        pbVigor.setProgress(33);
        pbVigor.setBgColor(getResources().getColor(R.color.pb_bg));
        pbVigor.setProgressColor(getResources().getColor(R.color.pb_progress_color));

        //头像
        lvHead = findViewById(R.id.lv_head);
        lvHead.setOnClickListener(this);
        //金币数
        tvGold = findViewById(R.id.tv_gold);
        //星星数
        tvStar = findViewById(R.id.tv_star);
        //喂食
        lvFeed = findViewById(R.id.lv_feed);
        lvFeed.setOnClickListener(this);

        //PK
        lvPk = findViewById(R.id.lv_pk);
        lvPk.setOnClickListener(this);

        //回家
        lvHome = findViewById(R.id.lv_home);
        lvHome.setOnClickListener(this);

        //好友
        lvFriends = findViewById(R.id.lv_friends);
        lvFriends.setOnClickListener(this);
        //消息
        lvMessage = findViewById(R.id.lv_message);
        lvMessage.setOnClickListener(this);

        //底图和背景公用
        ivClothing = findViewById(R.id.iv_clothing);
        //帽子
        ivHat = findViewById(R.id.iv_hat);
        //眼镜
        ivGrass = findViewById(R.id.iv_glass);
        //项链
        ivJingshi = findViewById(R.id.iv_jingshi);

        //动态配置屏幕右边顶部的各菜单栏大小
        int topItemSize = lvBottomItemWidth * 56 / 62;
        LinearLayout.LayoutParams lpTopItem = new LinearLayout.LayoutParams(topItemSize, topItemSize * 110 / 94);
        lpTopItem.bottomMargin = 12;
        lvFeed.setLayoutParams(lpTopItem);
        lvPk.setLayoutParams(lpTopItem);
        lvHome.setLayoutParams(lpTopItem);
        lvFriends.setLayoutParams(lpTopItem);
        lvMessage.setLayoutParams(lpTopItem);

        LinearLayout.LayoutParams lpTop = new LinearLayout.LayoutParams(topItemSize * 40 / 56, topItemSize * 40 / 56);
        lpTop.bottomMargin = 24;

        //宠物图片
        rlAllPet = findViewById(R.id.rl_all_pet);
        RelativeLayout.LayoutParams lpAll = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        lpAll.addRule(RelativeLayout.CENTER_HORIZONTAL);
        lpAll.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);

        //计算宠物在屏幕中的位置
        int screenHeight = ScreenUtils.getScreenHeight(this);
        int bottomMarginSize = screenHeight * 100 / 668;
        lpAll.bottomMargin = bottomMarginSize;
        rlAllPet.setLayoutParams(lpAll);

        //加载框布局
        rlLoading = findViewById(R.id.loading);
        rlLoading.setVisibility(View.VISIBLE);
    }

    /**
     * 请求服务器获取首页数据
     */
    private void http() {
        Map<String, String> map = new HashMap<>();
        map.put("type", "8");
        map.put("platform", "8");
        map.put("role", AccountUtils.getRole(this));
        map.put("acc", AccountUtils.getAccount(this));
        map.put("apptoken", AccountUtils.getToken(this));
        map.put("toacc", userid);
        map.put("fromname", SPUtil.getString(this, SpKeys.NAME));
        map.put("frompetname", SPUtil.getString(this, SpKeys.PETNAME));
        map.put("toname", toname);


        HttpUtils.post(HttpAdress.STHOME, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (null != rlLoading) {
                    rlLoading.setVisibility(View.GONE);
                }
                UiUtils.Toast(BaseApplication.ERROR, false);
            }

            @Override
            public void onResponse(String response, int id) {

                //背景设置完毕后隐藏加载框
//                if (null != rlLoading) {
//                    rlLoading.setVisibility(View.GONE);
//                }

                try {
                    if (!TextUtils.isEmpty(response)) {
                        json = response;
                        HomeInfo info = GsonUtil.jsonToBean(json, HomeInfo.class);
                        Log.i("test", "正确");
                        if (null != info) {
                            List<HomeInfo.DataBean> data = info.getData();
                            if (null != data && data.size() > 0) {
                                HomeInfo.DataBean dataBean = data.get(0);
                                //设置除了中间宠物部分的其它控件的数据
                                setOtherPageData(dataBean);
                                //设置宠物的相关信息
                                setPetInfo(info);

                                topetname = data.get(0).getPet_name();
                            }
                        }

                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    Log.i("test", "数据解析异常");
                }
            }
        });
    }


    /**
     * 设置除页面中间宠物信息的其它数据
     *
     * @param info
     */
    private void setOtherPageData(HomeInfo.DataBean info) {
        //背景
        ImageUtil.displayImage(this, lvBg, info.getBackground_url(), R.drawable.student_main_bg);

        //头像
        ImageUtil.displayImage(this, lvHead, info.getStudent_icon());

        //等级
        tvLever.setText("LV" + info.getLevel());

        //精力值
        tvEnergy.setText(info.getEnergy() + "/"+info.getMax_energy());

        //背景设置完毕后隐藏加载框,解决加载空白的问题
        if (null != rlLoading) {
            rlLoading.setVisibility(View.GONE);
        }
    }

    /**
     * 设置宠物的相关信息
     *
     * @param info
     */
    private void setPetInfo(HomeInfo info) {
        List<HomeInfo.DataFashion0Bean> dataFashion_0 = info.getDataFashion_0();
        List<HomeInfo.DataFashion1Bean> dataFashion_1 = info.getDataFashion_1();
        List<HomeInfo.DataFashion2Bean> dataFashion_2 = info.getDataFashion_2();
        List<HomeInfo.DataFashion3Bean> dataFashion_3 = info.getDataFashion_3();
        //套装
        if (dataFashion_0 == null || dataFashion_0.size() == 0) {
            //表示没有套装
            //获取拜访对象宠物类型，设置底图
            String type = info.getData().get(0).getPet_id();
            if ("1".equals(type)) {
                //狗
                ivClothing.setImageResource(R.drawable.stu_pet_dog);
            } else if ("2".equals(type)) {
                //猫
                ivClothing.setImageResource(R.drawable.stu_pet_cat);
            } else if ("3".equals(type)) {
                //怪物
                ivClothing.setImageResource(R.drawable.stu_pet_monster);
            } else if ("4".equals(type)) {
                //熊猫
                ivClothing.setImageResource(R.drawable.stu_pet_panda);
            }

            //设置帽子,眼镜,项链
            if (null != dataFashion_1 && dataFashion_1.size() > 0) {
                HomeInfo.DataFashion1Bean dataFashion1Bean = dataFashion_1.get(0);
                ImageUtil.displayImage(this, ivHat, dataFashion1Bean.getUrl());
            }

            if (null != dataFashion_2 && dataFashion_2.size() > 0) {
                HomeInfo.DataFashion2Bean dataFashion2Bean = dataFashion_2.get(0);
                ImageUtil.displayImage(this, ivHat, dataFashion2Bean.getUrl());
            }

            if (null != dataFashion_3 && dataFashion_3.size() > 0) {
                HomeInfo.DataFashion3Bean dataFashion3Bean = dataFashion_3.get(0);
                ImageUtil.displayImage(this, ivHat, dataFashion3Bean.getUrl());
            }

        } else {
            //有套装
            if (dataFashion_0.size() > 0) {
                HomeInfo.DataFashion0Bean dataFashion0Bean = dataFashion_0.get(0);
                ImageUtil.displayImage(this, ivClothing, dataFashion0Bean.getUrl());
            }
        }

        //让包含宠物的整体布局做屏幕两侧的动画效果处理
        startAnim();
    }


    /**
     * 执行动画的方法
     */
    private void startAnim() {
        //执行从中间到屏幕右边动画,然后执行从右往左的动画
        int disx = ScreenUtils.getScreenWidth(this) / 2 - UiUtils.dp2px(80);
        animator = ObjectAnimator.ofFloat(rlAllPet, "translationX", 0f, disx, -disx, 0f);
        animator.setInterpolator(new LinearInterpolator());
        animator.setRepeatCount(-1);
        animator.setDuration(4000);
        animator.start();
    }

    /**
     * 页面控件点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {

        int id = v.getId();

        if (id == R.id.lv_head) {
            //头像
            Intent intent = new Intent(this, StudentPersonInfoActivity.class);
            intent.putExtra("userid",userid);
            startActivity(intent);

        } else if (id == R.id.lv_feed) {
            //喂食
            Intent intent = new Intent(this, StudentFeedingActivity.class);
            intent.putExtra("userid",userid);
            intent.putExtra("toname",toname);
            intent.putExtra("topetname",topetname);
            startActivity(intent);

        } else if (id == R.id.lv_pk) {
            //宠物pk
            isPk(json);

        } else if (id == R.id.lv_friends) {
            //好友
            UiUtils.startActivity(this, StudentFriendsActivity.class);
            finish();
        } else if (id == R.id.lv_message) {
            //消息
            UiUtils.startActivity(this, StudentMessageActivity.class);
        } else if (id == R.id.lv_home) {
            //回家
            UiUtils.startActivity(this, StudentMainActivity.class);
            finish();
        }
    }

    /**
     * 判断能否PK
     */
    private void isPk(String json) {

        String acc = SPUtil.getString(this, SpKeys.ACCOUNT);
        String token = SPUtil.getString(this, SpKeys.TOKEN1);

        Map<String, String> map = new HashMap<>();
        map.put("type", "11");
        map.put("acc", acc);
        map.put("acc2", userid);
        map.put("role", "0");
        map.put("platform", "8");
        map.put("apptoken", token);

        Log.i("test","userid:"+userid+"apptoken:"+token);

        HttpUtils.post(HttpAdress.PK, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.i("test", "错误");
                UiUtils.Toast(BaseApplication.ERROR, false);

//                UiUtils.startActivity(StudentVisitFriendActivity.this, StudentPetPkActivity.class);
            }



            @Override
            public void onResponse(String response, int id) {
                showContent();
                ResultInfo info = null;
                try {
                    info = GsonUtil.jsonToBean(response, ResultInfo.class);
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.i("test", "数据解析异常");
                }
                Log.i("test", "jSON"+response);
                if (null != info) {
                    if ("200".equals(info.state)) {
                        //可PK
                        Intent intent = new Intent(StudentVisitFriendActivity.this,
                                StudentPetPkActivity.class);
                        intent.putExtra("json",json);
                        startActivity(intent);

                    } else if ("-1".equals(info.state)) {
                        UiUtils.Toast("操作失败", false);
                    } else if ("10086".equals(info.state)) {
                        UiUtils.Toast("本人PK次数超限", false);
                    } else if ("10087".equals(info.state)) {
                        UiUtils.Toast("对方PK次数超限", false);
                    } else if ("10088".equals(info.state)) {
                        UiUtils.Toast("本人精力值过低", false);
                    } else if ("10089".equals(info.state)) {
                        UiUtils.Toast("对方精力值过低", false);
                    } else if ("10090".equals(info.state)) {
                        UiUtils.Toast("对方今日已被本人PK", false);
                    }
                }
            }
        });
    }


    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onResume() {
        super.onResume();
        //执行动画
        if (!isFirst) {
            if (animator != null) {
                animator.resume();
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onPause() {
        super.onPause();
        //停止移动
        stopAnim();
    }


    /**
     * 停止动画的方法
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void stopAnim() {
        if (animator != null) {
            animator.pause();
        }
        isFirst = false;
    }

    @Override
    protected void onDestroy() {
        if (animator != null) {
            if (animator.isRunning()) {
                animator.cancel();
            }
            animator = null;
        }
        super.onDestroy();
    }
}
